# Copyright (c) 2009 Daropia Project (www.daropia.org)
#
# This file is part of Daropia and is available under the terms
# of the GNU General Public Licence version 2.0 or later.


# Handle user operations, including authentification
# Mounted to /user


class UserController < Controller
    # Helper to return to caller page after login
    helper :stack
    
    def index
        redirect r(:login)
    end

    # Handle user login
    # Serve two purposes : Display or handle the login form
    def login
        @title = "Connexion"

        # If we have parameters, we are in 'handle login form' mode
        if request.post?

            # Try to log in the user with the credentials
            user_login(request.subset(:login, :password))

            # In case of success, return to the caller page,
            # or the main index if none exists.
            if logged_in?
                flash[:message] = "Vous êtes maintenant connecté"
                answer '/'
            # Else return to the login form display
            else
                flash[:message] = "Erreur de connexion"
                redirect rs(:login)
            end
        end

        # Else, nothing to do : Ramaze will
        # display the login form normally
    end

    # Handle user logout
    def logout

        # If the user is connected, we disconnect him
        if logged_in?
            flash[:message] = "Vous êtes maintenant déconnecté"
            user_logout
        end

        # And we return to the calling page
        redirect_referer
    end

    # Handle user registration
    # Serve two purposes : Display or handle the registration form
    def register
        @title = "Création d'un compte"

        # If we have parameters, we hare in 'handle registration form' mode
        if request.post?
        
        	# Checking consistency
        	
        	if request['password'] != request['password_confirmation']
				flash[:message] = "Confirmation non cohérente"
				redirect UserController.r(:register)
			else
				
	            # Create the new User object
	            user = ::User.new
	            
	
	            # Fill up its properties
            	user.login = request['login']
	            user.email = request['email']
	            user.password = request['password']
	            user.password_confirmation = request['password_confirmation']
	            user.salt = Digest::SHA1.hexdigest("--#{Time.now.to_f}--#{user.email}")
	            # user.validated = false
	            user.creation_date = Time.now
	            	
	
	            # Try to save it
	            saved = user.save
	
	            if saved
	            	# send_email("register@daropia.org", "#{ user.email }", "Bienvenue", "Bonsoir, Votre création de compte à Daropia a bien été prise en compte. Merci de votre prise de position en faveur de la parodie.")
	                flash[:message] = "Compte créé"
	            else
	                flash[:message] = "Erreur lors de la création du compte"
	            end
	
	            # Return to main index
	            redirect MainController.r(:index)
	           end		
	           
        end
        
	           
        rescue Sequel::DatabaseError => e
        	if e.message == "SQLite3::SQLException: column login is not unique"
        	   	flash[:message] = "Nom d'utilisateur déjà enregistré"
        	elsif e.message == "SQLite3::SQLException: column email is not unique"
        	   	flash[:message] = "Adresse mail déjà enregistrée"
        	end
        

        # Else, nothing to do : Ramaze will
        # display the registration form normally
    end

    # Handles profile editing
    def edit
    	
    	require_login

    	# If we have parameters then we are in 'edit profile' mode
    	if request.post?

    		# Filling up
			user.name = request['name']
			user.surname = request['surname']
			user.address = request['address']
			user.gender = request['gender']
			user.dob = request['dob']
			user.avatar = request['avatar']
			user.description = request['description']
			user.signature = request['signature']

			# Try to save it
			saved = user.save

			if saved
				flash[:message] = "Profil modifié"
			else
				flash[:message] = "Erreur lors de la modification du profil"
			end

			# Return to main index
			redirect UserController.r(:show)
		end

		# Else, nothing to do : Ramaze will
		# display the profile view
	end

	# Shows the profile
	def show
		require_login
		
		@title = "Profil de " + user.login
    end

    # Handles password editing
    def edit_pass
    
    	require_login

    	# If we have parameters then we are in 'edit password' mode
    	if request.post?

    		# Checking consistency

    		if user.encrypt(request['old_pass']) != user.encrypted_password
				flash[:message] = "Mot de passe incorrect"
				redirect UserController.r(:edit_pass)
			elsif request['new_pass1'] != request['new_pass2']
				flash[:message] = "Confirmation non cohérente"
				redirect UserController.r(:edit_pass)
			else

    			# Replacing

    			user.encrypted_password = user.encrypt(request['new_pass1'])

				# Try to save it
				saved = user.save

				if saved
					flash[:message] = "Mot de passe modifié"
				else
					flash[:message] = "Erreur lors de la modification du mot de passe"
				end

				# Return to main index
				redirect UserController.r(:show)

			end

		end

		# Else, nothing to do : Ramaze will
		# display the profile view
	end

end
